<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>GORM入门指南 | 小狐档案库</title>
    <meta name="generator" content="VuePress 1.8.2">
    <link rel="icon" href="/favicon.ico">
    <meta name="description" content="学习资料">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.0c36f186.css" as="style"><link rel="preload" href="/assets/js/app.7029ddab.js" as="script"><link rel="preload" href="/assets/js/3.ebaa3085.js" as="script"><link rel="preload" href="/assets/js/1.8ce67e8c.js" as="script"><link rel="preload" href="/assets/js/49.fab43655.js" as="script"><link rel="prefetch" href="/assets/js/10.15c1f9c8.js"><link rel="prefetch" href="/assets/js/11.dc2fbddf.js"><link rel="prefetch" href="/assets/js/12.26ab1f36.js"><link rel="prefetch" href="/assets/js/13.6e1d4dbc.js"><link rel="prefetch" href="/assets/js/14.0cd48e80.js"><link rel="prefetch" href="/assets/js/15.74a9f029.js"><link rel="prefetch" href="/assets/js/16.24ef3382.js"><link rel="prefetch" href="/assets/js/17.c8a9bd0f.js"><link rel="prefetch" href="/assets/js/18.fbd494c2.js"><link rel="prefetch" href="/assets/js/19.f9a0df71.js"><link rel="prefetch" href="/assets/js/20.e6d0df38.js"><link rel="prefetch" href="/assets/js/21.932645cc.js"><link rel="prefetch" href="/assets/js/22.d6027dce.js"><link rel="prefetch" href="/assets/js/23.53bce141.js"><link rel="prefetch" href="/assets/js/24.ed3b8b64.js"><link rel="prefetch" href="/assets/js/25.ed88877e.js"><link rel="prefetch" href="/assets/js/26.f5ad24d5.js"><link rel="prefetch" href="/assets/js/27.64ad45b4.js"><link rel="prefetch" href="/assets/js/28.f308f8ab.js"><link rel="prefetch" href="/assets/js/29.4d95742d.js"><link rel="prefetch" href="/assets/js/30.0a867de0.js"><link rel="prefetch" href="/assets/js/31.f12def86.js"><link rel="prefetch" href="/assets/js/32.6b4fd8b7.js"><link rel="prefetch" href="/assets/js/33.4bb2aa9c.js"><link rel="prefetch" href="/assets/js/34.013e731c.js"><link rel="prefetch" href="/assets/js/35.6b263ef8.js"><link rel="prefetch" href="/assets/js/36.06acf3cc.js"><link rel="prefetch" href="/assets/js/37.fe72c29c.js"><link rel="prefetch" href="/assets/js/38.9b4e0bd6.js"><link rel="prefetch" href="/assets/js/39.0cde0408.js"><link rel="prefetch" href="/assets/js/4.9b5650bb.js"><link rel="prefetch" href="/assets/js/40.56bda9a8.js"><link rel="prefetch" href="/assets/js/41.007ae34c.js"><link rel="prefetch" href="/assets/js/42.bdaf414b.js"><link rel="prefetch" href="/assets/js/43.78d32d4e.js"><link rel="prefetch" href="/assets/js/44.a10cf8a5.js"><link rel="prefetch" href="/assets/js/45.19e14721.js"><link rel="prefetch" href="/assets/js/46.57ebcf06.js"><link rel="prefetch" href="/assets/js/47.9a513ffe.js"><link rel="prefetch" href="/assets/js/48.245b165a.js"><link rel="prefetch" href="/assets/js/5.a16ef7f8.js"><link rel="prefetch" href="/assets/js/50.48c191fd.js"><link rel="prefetch" href="/assets/js/51.28a94b0e.js"><link rel="prefetch" href="/assets/js/52.e783fbf9.js"><link rel="prefetch" href="/assets/js/53.2f0e960e.js"><link rel="prefetch" href="/assets/js/54.577ff54e.js"><link rel="prefetch" href="/assets/js/55.4bb99598.js"><link rel="prefetch" href="/assets/js/56.e820e954.js"><link rel="prefetch" href="/assets/js/57.0cea0cfa.js"><link rel="prefetch" href="/assets/js/58.e31cfcd0.js"><link rel="prefetch" href="/assets/js/59.458ab168.js"><link rel="prefetch" href="/assets/js/6.7da424ba.js"><link rel="prefetch" href="/assets/js/60.e9caace2.js"><link rel="prefetch" href="/assets/js/61.0b61afdb.js"><link rel="prefetch" href="/assets/js/62.c240acab.js"><link rel="prefetch" href="/assets/js/63.71cd2a97.js"><link rel="prefetch" href="/assets/js/64.977ea29b.js"><link rel="prefetch" href="/assets/js/65.79b2d62a.js"><link rel="prefetch" href="/assets/js/66.8da69071.js"><link rel="prefetch" href="/assets/js/67.fdc57d7e.js"><link rel="prefetch" href="/assets/js/68.d43eabe9.js"><link rel="prefetch" href="/assets/js/7.6e92edd1.js"><link rel="prefetch" href="/assets/js/8.2389170b.js"><link rel="prefetch" href="/assets/js/9.77841f24.js">
    <link rel="stylesheet" href="/assets/css/0.styles.0c36f186.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container" data-v-1156296a><div data-v-1156296a><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-1156296a data-v-1156296a><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-4e82dffc data-v-1156296a data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>小狐档案库</h3> <p class="description" data-v-4e82dffc data-v-4e82dffc>学习资料</p> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div class="hide" data-v-1156296a><header class="navbar" data-v-1156296a><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="小狐档案库" class="logo"> <span class="site-name">小狐档案库</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-1156296a></div> <aside class="sidebar" data-v-1156296a><div class="personal-info-wrapper" data-v-828910c6 data-v-1156296a><img src="/avatar.jpg" alt="author-avatar" class="personal-img" data-v-828910c6> <h3 class="name" data-v-828910c6>
    小狐
  </h3> <div class="num" data-v-828910c6><div data-v-828910c6><h3 data-v-828910c6>58</h3> <h6 data-v-828910c6>Articles</h6></div> <div data-v-828910c6><h3 data-v-828910c6>20</h3> <h6 data-v-828910c6>Tags</h6></div></div> <ul class="social-links" data-v-828910c6></ul> <hr data-v-828910c6></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav> <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>go语言学习</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>go语言基础学习</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gin</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>数据库操作</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading open"><span>gorm</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/blogs/GO/go_web/gorm/gorm_cross.html" aria-current="page" class="active sidebar-link">GORM入门指南</a></li><li><a href="/blogs/GO/go_web/gorm/gorm_crud.html" class="sidebar-link">GORM CRUD指南</a></li></ul></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gorm</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>NoSql</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>消息队列</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>go三方库</span> <span class="arrow right"></span></p> <!----></section></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-4e82dffc data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>GORM入门指南</h3> <!----> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div data-v-1156296a><main class="page"><section><div class="page-title"><h1 class="title">GORM入门指南</h1> <div data-v-1ff7123e><i class="iconfont reco-account" data-v-1ff7123e><span data-v-1ff7123e>小狐</span></i> <i class="iconfont reco-date" data-v-1ff7123e><span data-v-1ff7123e>9/4/2021</span></i> <!----> <i class="tags iconfont reco-tag" data-v-1ff7123e><span class="tag-item" data-v-1ff7123e>GO</span><span class="tag-item" data-v-1ff7123e>GO框架库</span><span class="tag-item" data-v-1ff7123e>gorm</span></i></div></div> <div class="theme-reco-content content__default"><h1 id="gorm入门指南"><a href="#gorm入门指南" class="header-anchor">#</a> GORM入门指南</h1> <p>gorm是一个使用Go语言编写的ORM框架。它文档齐全，对开发者友好，支持主流数据库。</p> <p><strong>注意：文中使用的gorm版本有极大概率与你正在使用的不一致，为了更好的使用gorm请移步官方中文文档：https://gorm.io/zh_CN/docs/</strong></p> <h2 id="gorm介绍"><a href="#gorm介绍" class="header-anchor">#</a> gorm介绍</h2> <p><a href="https://github.com/jinzhu/gorm" target="_blank" rel="noopener noreferrer">Github GORM<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <p><a href="https://gorm.io/zh_CN/" target="_blank" rel="noopener noreferrer">中文官方网站<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>内含十分齐全的中文文档，有了它你甚至不需要再继续向下阅读本文。</p> <h2 id="安装"><a href="#安装" class="header-anchor">#</a> 安装</h2> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>go get -u github.com/jinzhu/gorm
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h2 id="连接数据库"><a href="#连接数据库" class="header-anchor">#</a> 连接数据库</h2> <p>连接不同的数据库都需要导入对应数据的驱动程序，<code>GORM</code>已经贴心的为我们包装了一些驱动程序，只需要按如下方式导入需要的数据库驱动即可：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/mysql&quot;</span>
<span class="token comment">// import _ &quot;github.com/jinzhu/gorm/dialects/postgres&quot;</span>
<span class="token comment">// import _ &quot;github.com/jinzhu/gorm/dialects/sqlite&quot;</span>
<span class="token comment">// import _ &quot;github.com/jinzhu/gorm/dialects/mssql&quot;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><h3 id="连接mysql"><a href="#连接mysql" class="header-anchor">#</a> 连接MySQL</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token punctuation">(</span>
  <span class="token string">&quot;github.com/jinzhu/gorm&quot;</span>
  <span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/mysql&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  db<span class="token punctuation">,</span> err <span class="token operator">:=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;mysql&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;user:password@(localhost)/dbname?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot;</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><h3 id="连接postgresql"><a href="#连接postgresql" class="header-anchor">#</a> 连接PostgreSQL</h3> <p>基本代码同上，注意引入对应<code>postgres</code>驱动并正确指定<code>gorm.Open()</code>参数。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token punctuation">(</span>
  <span class="token string">&quot;github.com/jinzhu/gorm&quot;</span>
  <span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/postgres&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  db<span class="token punctuation">,</span> err <span class="token operator">:=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;postgres&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;host=myhost port=myport user=gorm dbname=gorm password=mypassword&quot;</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><h3 id="连接sqlite3"><a href="#连接sqlite3" class="header-anchor">#</a> 连接Sqlite3</h3> <p>基本代码同上，注意引入对应<code>sqlite</code>驱动并正确指定<code>gorm.Open()</code>参数。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token punctuation">(</span>
  <span class="token string">&quot;github.com/jinzhu/gorm&quot;</span>
  <span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/sqlite&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  db<span class="token punctuation">,</span> err <span class="token operator">:=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;sqlite3&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;/tmp/gorm.db&quot;</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><h3 id="连接sql-server"><a href="#连接sql-server" class="header-anchor">#</a> 连接SQL Server</h3> <p>基本代码同上，注意引入对应<code>mssql</code>驱动并正确指定<code>gorm.Open()</code>参数。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token punctuation">(</span>
  <span class="token string">&quot;github.com/jinzhu/gorm&quot;</span>
  <span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/mssql&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  db<span class="token punctuation">,</span> err <span class="token operator">:=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;mssql&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;sqlserver://username:password@localhost:1433?database=dbname&quot;</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><h2 id="gorm基本示例"><a href="#gorm基本示例" class="header-anchor">#</a> GORM基本示例</h2> <p><strong>注意:</strong></p> <ol><li>本文以MySQL数据库为例，讲解GORM各项功能的主要使用方法。</li> <li>往下阅读本文前，你需要有一个能够成功连接上的MySQL数据库实例。</li></ol> <h3 id="docker快速创建mysql实例"><a href="#docker快速创建mysql实例" class="header-anchor">#</a> Docker快速创建MySQL实例</h3> <p>很多同学如果不会安装MySQL或者懒得安装MySQL，可以使用一下命令快速运行一个MySQL8.0.19实例，当然前提是你要有docker环境…</p> <p>在本地的<code>13306</code>端口运行一个名为<code>mysql8019</code>，root用户名密码为<code>root1234</code>的MySQL容器环境:</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>docker run --name mysql8019 -p <span class="token number">13306</span>:3306 -e <span class="token assign-left variable">MYSQL_ROOT_PASSWORD</span><span class="token operator">=</span>root1234 -d mysql:8.0.19
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>在另外启动一个<code>MySQL Client</code>连接上面的MySQL环境，密码为上一步指定的密码<code>root1234</code>:</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>docker run -it --network <span class="token function">host</span> --rm mysql mysql -h127.0.0.1 -P13306 --default-character-set<span class="token operator">=</span>utf8mb4 -uroot -p
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="创建数据库"><a href="#创建数据库" class="header-anchor">#</a> 创建数据库</h3> <p>在使用GORM前手动创建数据库<code>db1</code>：</p> <div class="language-mysql line-numbers-mode"><pre class="language-text"><code>CREATE DATABASE db1;
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="gorm操作mysql"><a href="#gorm操作mysql" class="header-anchor">#</a> GORM操作MySQL</h3> <p>使用GORM连接上面的<code>db1</code>进行创建、查询、更新、删除操作。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;github.com/jinzhu/gorm&quot;</span>
	<span class="token boolean">_</span> <span class="token string">&quot;github.com/jinzhu/gorm/dialects/mysql&quot;</span>
<span class="token punctuation">)</span>

<span class="token comment">// UserInfo 用户信息</span>
<span class="token keyword">type</span> UserInfo <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	ID <span class="token builtin">uint</span>
	Name <span class="token builtin">string</span>
	Gender <span class="token builtin">string</span>
	Hobby <span class="token builtin">string</span>
<span class="token punctuation">}</span>


<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	db<span class="token punctuation">,</span> err <span class="token operator">:=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;mysql&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;root:root1234@(127.0.0.1:13306)/db1?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err<span class="token operator">!=</span> <span class="token boolean">nil</span><span class="token punctuation">{</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// 自动迁移</span>
	db<span class="token punctuation">.</span><span class="token function">AutoMigrate</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>UserInfo<span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>

	u1 <span class="token operator">:=</span> UserInfo<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">&quot;七米&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;男&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;篮球&quot;</span><span class="token punctuation">}</span>
	u2 <span class="token operator">:=</span> UserInfo<span class="token punctuation">{</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token string">&quot;沙河娜扎&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;女&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;足球&quot;</span><span class="token punctuation">}</span>
	<span class="token comment">// 创建记录</span>
	db<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u1<span class="token punctuation">)</span>
	db<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u2<span class="token punctuation">)</span>
	<span class="token comment">// 查询</span>
	<span class="token keyword">var</span> u <span class="token operator">=</span> <span class="token function">new</span><span class="token punctuation">(</span>UserInfo<span class="token punctuation">)</span>
	db<span class="token punctuation">.</span><span class="token function">First</span><span class="token punctuation">(</span>u<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;%#v\n&quot;</span><span class="token punctuation">,</span> u<span class="token punctuation">)</span>

	<span class="token keyword">var</span> uu UserInfo
	db<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>uu<span class="token punctuation">,</span> <span class="token string">&quot;hobby=?&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;足球&quot;</span><span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;%#v\n&quot;</span><span class="token punctuation">,</span> uu<span class="token punctuation">)</span>

	<span class="token comment">// 更新</span>
	db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span><span class="token string">&quot;hobby&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;双色球&quot;</span><span class="token punctuation">)</span>
	<span class="token comment">// 删除</span>
	db<span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br></div></div><h2 id="gorm-model定义"><a href="#gorm-model定义" class="header-anchor">#</a> GORM Model定义</h2> <p>在使用ORM工具时，通常我们需要在代码中定义模型（Models）与数据库中的数据表进行映射，在GORM中模型（Models）通常是正常定义的结构体、基本的go类型或它们的指针。 同时也支持<code>sql.Scanner</code>及<code>driver.Valuer</code>接口（interfaces）。</p> <h3 id="gorm-model"><a href="#gorm-model" class="header-anchor">#</a> gorm.Model</h3> <p>为了方便模型定义，GORM内置了一个<code>gorm.Model</code>结构体。<code>gorm.Model</code>是一个包含了<code>ID</code>, <code>CreatedAt</code>, <code>UpdatedAt</code>, <code>DeletedAt</code>四个字段的Golang结构体。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// gorm.Model 定义</span>
<span class="token keyword">type</span> Model <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  ID        <span class="token builtin">uint</span> <span class="token string">`gorm:&quot;primary_key&quot;`</span>
  CreatedAt time<span class="token punctuation">.</span>Time
  UpdatedAt time<span class="token punctuation">.</span>Time
  DeletedAt <span class="token operator">*</span>time<span class="token punctuation">.</span>Time
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>你可以将它嵌入到你自己的模型中：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 将 `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`字段注入到`User`模型中</span>
<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  gorm<span class="token punctuation">.</span>Model
  Name <span class="token builtin">string</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>当然你也可以完全自己定义模型：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 不使用gorm.Model，自行定义模型</span>
<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  ID   <span class="token builtin">int</span>
  Name <span class="token builtin">string</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h3 id="模型定义示例"><a href="#模型定义示例" class="header-anchor">#</a> 模型定义示例</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  gorm<span class="token punctuation">.</span>Model
  Name         <span class="token builtin">string</span>
  Age          sql<span class="token punctuation">.</span>NullInt64
  Birthday     <span class="token operator">*</span>time<span class="token punctuation">.</span>Time
  Email        <span class="token builtin">string</span>  <span class="token string">`gorm:&quot;type:varchar(100);unique_index&quot;`</span>
  Role         <span class="token builtin">string</span>  <span class="token string">`gorm:&quot;size:255&quot;`</span> <span class="token comment">// 设置字段大小为255</span>
  MemberNumber <span class="token operator">*</span><span class="token builtin">string</span> <span class="token string">`gorm:&quot;unique;not null&quot;`</span> <span class="token comment">// 设置会员号（member number）唯一并且不为空</span>
  Num          <span class="token builtin">int</span>     <span class="token string">`gorm:&quot;AUTO_INCREMENT&quot;`</span> <span class="token comment">// 设置 num 为自增类型</span>
  Address      <span class="token builtin">string</span>  <span class="token string">`gorm:&quot;index:addr&quot;`</span> <span class="token comment">// 给address字段创建名为addr的索引</span>
  IgnoreMe     <span class="token builtin">int</span>     <span class="token string">`gorm:&quot;-&quot;`</span> <span class="token comment">// 忽略本字段</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><h3 id="结构体标记-tags"><a href="#结构体标记-tags" class="header-anchor">#</a> 结构体标记（tags）</h3> <p>使用结构体声明模型时，标记（tags）是可选项。gorm支持以下标记:</p> <h4 id="支持的结构体标记-struct-tags"><a href="#支持的结构体标记-struct-tags" class="header-anchor">#</a> 支持的结构体标记（Struct tags）</h4> <table><thead><tr><th style="text-align:center;">结构体标记（Tag）</th> <th style="text-align:center;">描述</th></tr></thead> <tbody><tr><td style="text-align:center;">Column</td> <td style="text-align:center;">指定列名</td></tr> <tr><td style="text-align:center;">Type</td> <td style="text-align:center;">指定列数据类型</td></tr> <tr><td style="text-align:center;">Size</td> <td style="text-align:center;">指定列大小, 默认值255</td></tr> <tr><td style="text-align:center;">PRIMARY_KEY</td> <td style="text-align:center;">将列指定为主键</td></tr> <tr><td style="text-align:center;">UNIQUE</td> <td style="text-align:center;">将列指定为唯一</td></tr> <tr><td style="text-align:center;">DEFAULT</td> <td style="text-align:center;">指定列默认值</td></tr> <tr><td style="text-align:center;">PRECISION</td> <td style="text-align:center;">指定列精度</td></tr> <tr><td style="text-align:center;">NOT NULL</td> <td style="text-align:center;">将列指定为非 NULL</td></tr> <tr><td style="text-align:center;">AUTO_INCREMENT</td> <td style="text-align:center;">指定列是否为自增类型</td></tr> <tr><td style="text-align:center;">INDEX</td> <td style="text-align:center;">创建具有或不带名称的索引, 如果多个索引同名则创建复合索引</td></tr> <tr><td style="text-align:center;">UNIQUE_INDEX</td> <td style="text-align:center;">和 <code>INDEX</code> 类似，只不过创建的是唯一索引</td></tr> <tr><td style="text-align:center;">EMBEDDED</td> <td style="text-align:center;">将结构设置为嵌入</td></tr> <tr><td style="text-align:center;">EMBEDDED_PREFIX</td> <td style="text-align:center;">设置嵌入结构的前缀</td></tr> <tr><td style="text-align:center;">-</td> <td style="text-align:center;">忽略此字段</td></tr></tbody></table> <h4 id="关联相关标记-tags"><a href="#关联相关标记-tags" class="header-anchor">#</a> 关联相关标记（tags）</h4> <table><thead><tr><th style="text-align:center;">结构体标记（Tag）</th> <th style="text-align:center;">描述</th></tr></thead> <tbody><tr><td style="text-align:center;">MANY2MANY</td> <td style="text-align:center;">指定连接表</td></tr> <tr><td style="text-align:center;">FOREIGNKEY</td> <td style="text-align:center;">设置外键</td></tr> <tr><td style="text-align:center;">ASSOCIATION_FOREIGNKEY</td> <td style="text-align:center;">设置关联外键</td></tr> <tr><td style="text-align:center;">POLYMORPHIC</td> <td style="text-align:center;">指定多态类型</td></tr> <tr><td style="text-align:center;">POLYMORPHIC_VALUE</td> <td style="text-align:center;">指定多态值</td></tr> <tr><td style="text-align:center;">JOINTABLE_FOREIGNKEY</td> <td style="text-align:center;">指定连接表的外键</td></tr> <tr><td style="text-align:center;">ASSOCIATION_JOINTABLE_FOREIGNKEY</td> <td style="text-align:center;">指定连接表的关联外键</td></tr> <tr><td style="text-align:center;">SAVE_ASSOCIATIONS</td> <td style="text-align:center;">是否自动完成 save 的相关操作</td></tr> <tr><td style="text-align:center;">ASSOCIATION_AUTOUPDATE</td> <td style="text-align:center;">是否自动完成 update 的相关操作</td></tr> <tr><td style="text-align:center;">ASSOCIATION_AUTOCREATE</td> <td style="text-align:center;">是否自动完成 create 的相关操作</td></tr> <tr><td style="text-align:center;">ASSOCIATION_SAVE_REFERENCE</td> <td style="text-align:center;">是否自动完成引用的 save 的相关操作</td></tr> <tr><td style="text-align:center;">PRELOAD</td> <td style="text-align:center;">是否自动完成预加载的相关操作</td></tr></tbody></table> <h2 id="主键、表名、列名的约定"><a href="#主键、表名、列名的约定" class="header-anchor">#</a> 主键、表名、列名的约定</h2> <h3 id="主键-primary-key"><a href="#主键-primary-key" class="header-anchor">#</a> 主键（Primary Key）</h3> <p>GORM 默认会使用名为ID的字段作为表的主键。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  ID   <span class="token builtin">string</span> <span class="token comment">// 名为`ID`的字段会默认作为表的主键</span>
  Name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token comment">// 使用`AnimalID`作为主键</span>
<span class="token keyword">type</span> Animal <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  AnimalID <span class="token builtin">int64</span> <span class="token string">`gorm:&quot;primary_key&quot;`</span>
  Name     <span class="token builtin">string</span>
  Age      <span class="token builtin">int64</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><h3 id="表名-table-name"><a href="#表名-table-name" class="header-anchor">#</a> 表名（Table Name）</h3> <p>表名默认就是结构体名称的复数，例如：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span><span class="token punctuation">}</span> <span class="token comment">// 默认表名是 `users`</span>

<span class="token comment">// 将 User 的表名设置为 `profiles`</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>User<span class="token punctuation">)</span> <span class="token function">TableName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token string">&quot;profiles&quot;</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>u User<span class="token punctuation">)</span> <span class="token function">TableName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> u<span class="token punctuation">.</span>Role <span class="token operator">==</span> <span class="token string">&quot;admin&quot;</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token string">&quot;admin_users&quot;</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token string">&quot;users&quot;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token comment">// 禁用默认表名的复数形式，如果置为 true，则 `User` 的默认表名是 `user`</span>
db<span class="token punctuation">.</span><span class="token function">SingularTable</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>也可以通过<code>Table()</code>指定表名：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 使用User结构体创建名为`deleted_users`的表</span>
db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">&quot;deleted_users&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">CreateTable</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>User<span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> deleted_users <span class="token punctuation">[</span><span class="token punctuation">]</span>User
db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">&quot;deleted_users&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>deleted_users<span class="token punctuation">)</span>
<span class="token comment">//// SELECT * FROM deleted_users;</span>

db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">&quot;deleted_users&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">&quot;name = ?&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;jinzhu&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">//// DELETE FROM deleted_users WHERE name = 'jinzhu';</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>GORM还支持更改默认表名称规则：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code>gorm<span class="token punctuation">.</span>DefaultTableNameHandler <span class="token operator">=</span> <span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>gorm<span class="token punctuation">.</span>DB<span class="token punctuation">,</span> defaultTableName <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span>  <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token string">&quot;prefix_&quot;</span> <span class="token operator">+</span> defaultTableName<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><h3 id="列名-column-name"><a href="#列名-column-name" class="header-anchor">#</a> 列名（Column Name）</h3> <p>列名由字段名称进行下划线分割来生成</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  ID        <span class="token builtin">uint</span>      <span class="token comment">// column name is `id`</span>
  Name      <span class="token builtin">string</span>    <span class="token comment">// column name is `name`</span>
  Birthday  time<span class="token punctuation">.</span>Time <span class="token comment">// column name is `birthday`</span>
  CreatedAt time<span class="token punctuation">.</span>Time <span class="token comment">// column name is `created_at`</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>可以使用结构体tag指定列名：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> Animal <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  AnimalId    <span class="token builtin">int64</span>     <span class="token string">`gorm:&quot;column:beast_id&quot;`</span>         <span class="token comment">// set column name to `beast_id`</span>
  Birthday    time<span class="token punctuation">.</span>Time <span class="token string">`gorm:&quot;column:day_of_the_beast&quot;`</span> <span class="token comment">// set column name to `day_of_the_beast`</span>
  Age         <span class="token builtin">int64</span>     <span class="token string">`gorm:&quot;column:age_of_the_beast&quot;`</span> <span class="token comment">// set column name to `age_of_the_beast`</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h3 id="时间戳跟踪"><a href="#时间戳跟踪" class="header-anchor">#</a> 时间戳跟踪</h3> <h4 id="createdat"><a href="#createdat" class="header-anchor">#</a> CreatedAt</h4> <p>如果模型有 <code>CreatedAt</code>字段，该字段的值将会是初次创建记录的时间。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code>db<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>user<span class="token punctuation">)</span> <span class="token comment">// `CreatedAt`将会是当前时间</span>

<span class="token comment">// 可以使用`Update`方法来改变`CreateAt`的值</span>
db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>user<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span><span class="token string">&quot;CreatedAt&quot;</span><span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><h4 id="updatedat"><a href="#updatedat" class="header-anchor">#</a> UpdatedAt</h4> <p>如果模型有<code>UpdatedAt</code>字段，该字段的值将会是每次更新记录的时间。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code>db<span class="token punctuation">.</span><span class="token function">Save</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>user<span class="token punctuation">)</span> <span class="token comment">// `UpdatedAt`将会是当前时间</span>

db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>user<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span><span class="token string">&quot;name&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;jinzhu&quot;</span><span class="token punctuation">)</span> <span class="token comment">// `UpdatedAt`将会是当前时间</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><h4 id="deletedat"><a href="#deletedat" class="header-anchor">#</a> DeletedAt</h4> <p>如果模型有<code>DeletedAt</code>字段，调用<code>Delete</code>删除该记录时，将会设置<code>DeletedAt</code>字段为当前时间，而不是直接将记录从数据库中删除。</p></div></section> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">2021-9-2: </span> <span class="time">9/3/2021, 6:20:18 PM</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev"><a href="/blogs/GO/go_mysql/go_sqlx_2.html" class="prev">
            GO使用sqlx批量插入数据的若干方法
          </a></span> <span class="next"><a href="/blogs/GO/go_web/gorm/gorm_crud.html">
            GORM CRUD指南
          </a></span></p></div> <div class="comments-wrapper"><!----></div> <ul class="side-bar sub-sidebar-wrapper" style="width:12rem;" data-v-70334359><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#gorm介绍" class="sidebar-link reco-side-gorm介绍" data-v-70334359>gorm介绍</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#安装" class="sidebar-link reco-side-安装" data-v-70334359>安装</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#连接数据库" class="sidebar-link reco-side-连接数据库" data-v-70334359>连接数据库</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#连接mysql" class="sidebar-link reco-side-连接mysql" data-v-70334359>连接MySQL</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#连接postgresql" class="sidebar-link reco-side-连接postgresql" data-v-70334359>连接PostgreSQL</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#连接sqlite3" class="sidebar-link reco-side-连接sqlite3" data-v-70334359>连接Sqlite3</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#连接sql-server" class="sidebar-link reco-side-连接sql-server" data-v-70334359>连接SQL Server</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#gorm基本示例" class="sidebar-link reco-side-gorm基本示例" data-v-70334359>GORM基本示例</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#docker快速创建mysql实例" class="sidebar-link reco-side-docker快速创建mysql实例" data-v-70334359>Docker快速创建MySQL实例</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#创建数据库" class="sidebar-link reco-side-创建数据库" data-v-70334359>创建数据库</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#gorm操作mysql" class="sidebar-link reco-side-gorm操作mysql" data-v-70334359>GORM操作MySQL</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#gorm-model定义" class="sidebar-link reco-side-gorm-model定义" data-v-70334359>GORM Model定义</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#gorm-model" class="sidebar-link reco-side-gorm-model" data-v-70334359>gorm.Model</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#模型定义示例" class="sidebar-link reco-side-模型定义示例" data-v-70334359>模型定义示例</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#结构体标记-tags" class="sidebar-link reco-side-结构体标记-tags" data-v-70334359>结构体标记（tags）</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#主键、表名、列名的约定" class="sidebar-link reco-side-主键、表名、列名的约定" data-v-70334359>主键、表名、列名的约定</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#主键-primary-key" class="sidebar-link reco-side-主键-primary-key" data-v-70334359>主键（Primary Key）</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#表名-table-name" class="sidebar-link reco-side-表名-table-name" data-v-70334359>表名（Table Name）</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#列名-column-name" class="sidebar-link reco-side-列名-column-name" data-v-70334359>列名（Column Name）</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_web/gorm/gorm_cross.html#时间戳跟踪" class="sidebar-link reco-side-时间戳跟踪" data-v-70334359>时间戳跟踪</a></li></ul></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><!----><canvas id="vuepress-canvas-cursor"></canvas></div></div>
    <script src="/assets/js/app.7029ddab.js" defer></script><script src="/assets/js/3.ebaa3085.js" defer></script><script src="/assets/js/1.8ce67e8c.js" defer></script><script src="/assets/js/49.fab43655.js" defer></script>
  </body>
</html>
